﻿//
// Lightbox Gallery Module for DotNetNuke
// Project Contributors - Will Strohl (http://www.WillStrohl.com), Armand Datema (http://www.schwingsoft.com)
//
//Copyright (c) 2009-2013, Will Strohl
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are 
//permitted provided that the following conditions are met:
//
//Redistributions of source code must retain the above copyright notice, this list of 
//conditions and the following disclaimer.
//
//Redistributions in binary form must reproduce the above copyright notice, this list 
//of conditions and the following disclaimer in the documentation and/or other 
//materials provided with the distribution.
//
//Neither the name of Will Strohl, Armand Datema, Lightbox Gallery, nor the names of its contributors may be 
//used to endorse or promote products derived from this software without specific prior 
//written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
//EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
//OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
//SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
//TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
//BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
//CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
//DAMAGE.
//

//INSTANT C# NOTE: Formerly VB project-level imports:

using System.Globalization;
using System.Linq;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Users;
using DotNetNuke.Services.Localization;
using DotNetNuke.Entities.Modules;

namespace WillStrohl.Modules.Lightbox
{

    public class WnsPortalModuleBase : PortalModuleBase
    {

        #region Private Members

        private const string EDIT_KEY = "Edit";

        private int p_GroupIdParam = Null.NullInteger;
        private int p_UserIdParam = Null.NullInteger;
        private UserRoleInfo p_CurrentSocialGroup = null;

        #endregion

        #region Properties 

        protected int GroupIdParam
        {
            get
            {
                if (p_GroupIdParam == Null.NullInteger)
                {
                    var groupId = Request.QueryString["GroupId"];
                    if (groupId != null)
                    {
                        int.TryParse(groupId.ToString(CultureInfo.InvariantCulture), out p_GroupIdParam);
                    }
                }

                return p_GroupIdParam;
            }
        }

        protected int UserIdParam
        {
            get
            {
                if (p_UserIdParam == Null.NullInteger)
                {
                    var userId = Request.QueryString["UserId"];
                    if (userId != null)
                    {
                        int.TryParse(userId.ToString(CultureInfo.InvariantCulture), out p_UserIdParam);
                    }
                }

                return p_UserIdParam;
            }
        }

        protected UserRoleInfo CurrentSocialGroup
        {
            get
            {
                if (UserInfo != null && UserInfo.UserID > Null.NullInteger)
                {
                    var currentGroup = from r in UserInfo.Social.Roles
                                       where r.RoleID == GroupIdParam
                                       select r;

                    if (currentGroup.Any())
                    {
                        p_CurrentSocialGroup = currentGroup.FirstOrDefault();
                    }
                }

                return p_CurrentSocialGroup;
            }
        }

        #endregion

        #region Event Handlers

        public WnsPortalModuleBase()
        {

            //INSTANT C# NOTE: Converted event handler wireups:
            this.Load += new System.EventHandler(Page_Load);
        }

        private void Page_Load(object sender, System.EventArgs e)
        {

            // request that the DNN framework load the jQuery script into the markup
            DotNetNuke.Framework.jQuery.RequestDnnPluginsRegistration();

        }

        #endregion

        #region Localization

        protected string GetLocalizedString(string LocalizationKey)
        {
            if (!(string.IsNullOrEmpty(LocalizationKey)))
            {
                return Localization.GetString(LocalizationKey, this.LocalResourceFile);
            }
            else
            {
                return string.Empty;
            }
        }

        protected string GetLocalizedString(string LocalizationKey, string LocalResourceFilePath)
        {
            if (!(string.IsNullOrEmpty(LocalizationKey)))
            {
                return Localization.GetString(LocalizationKey, LocalResourceFilePath);
            }
            else
            {
                return string.Empty;
            }
        }

        #endregion

        #region URL Methods

        protected string GetSocialParameters()
        {
            var param = string.Empty;

            if (UserIdParam > Null.NullInteger)
            {
                param = string.Format("UserId={0}", UserIdParam);
            }

            if (GroupIdParam > Null.NullInteger)
            {
                if (string.IsNullOrEmpty(param))
                {
                    param = string.Format("GroupId={0}", GroupIdParam);
                }
                else
                {
                    param = string.Concat(param, string.Format("&GroupId={0}", GroupIdParam));
                }
            }

            return param;
        }

        protected string GetDefaultViewUrl()
        {
            return Globals.NavigateURL(TabId, string.Empty, GetSocialParameters());
        }

        protected string GetEditUrl()
        {
            return GetEditUrl(EDIT_KEY, null);
        }

        protected string GetEditUrl(string ViewKey)
        {
            return GetEditUrl(ViewKey, null);
        }

        protected string GetEditUrl(string ViewKey, object GalleryId)
        {
            var param = GetSocialParameters();

            if (GalleryId != null)
            {
                // add the social params
                if (!string.IsNullOrEmpty(param))
                {
                    param = string.Concat(string.Format("AlbumId={0}&", GalleryId), param);
                }
                else
                {
                    param = string.Format("AlbumId={0}", GalleryId);
                }

                // return the edit url for an existing gallery/album
                return EditUrl(string.Empty, string.Empty, ViewKey, param);
            }
            else
            {
                // add the social params
                if (!string.IsNullOrEmpty(param))
                {
                    // return the edit url for a new gallery/album
                    return EditUrl(string.Empty, string.Empty, ViewKey, param);
                }
                else
                {
                    // return the edit url for a new gallery/album
                    return EditUrl(string.Empty, string.Empty, ViewKey);
                }
            }
        }

        protected string GetReorderUrl(object GalleryId)
        {
            if (GalleryId != null)
            {
                var param = GetSocialParameters();

                // add the social params
                if (!string.IsNullOrEmpty(param))
                {
                    param = string.Concat(string.Format("Album={0}&", GalleryId), param);
                }
                else
                {
                    param = string.Format("Album={0}", GalleryId);
                }

                // return the edit url
                return EditUrl(string.Empty, string.Empty, "ChangeImageOrder", param);
            }
            else
            {
                return "#";
            }
        }

        protected string GetImageEditUrl(ImageInfo oImage)
        {

            var param = GetSocialParameters();

            // add the social params
            if (!string.IsNullOrEmpty(param))
            {
                param = string.Concat(string.Format("Image={0}&Album={1}&", oImage.ImageId, oImage.LightboxId), param);
            }
            else
            {
                param = string.Format("Image={0}&Album={1}", oImage.ImageId, oImage.LightboxId);
            }

            // return the edit url
            return EditUrl(string.Empty, string.Empty, "EditImage", param);

        }

        #endregion

        #region Security

        protected bool IsInSocialMode()
        {
            // is on the profile page
            if (((ModuleContext.PortalSettings.ActiveTab.ParentId == ModuleContext.PortalSettings.UserTabId) || (ModuleContext.TabId == ModuleContext.PortalSettings.UserTabId)) && UserIdParam > Null.NullInteger)
            {
                return true;
            }

            // is on a group page
            if (GroupIdParam > Null.NullInteger)
            {
                if (CurrentSocialGroup != null && CurrentSocialGroup.IsOwner)
                {
                    return true;
                }
            }

            return false;
        }

        protected bool ShowSocialEditFeatures()
        {
            /*
             * Allow the button to be visible if:
             * 1. Admin is logged in
             * 2. Group owner is logged in and the GroupId matches
             * 3. Profile owner is logged in and the UserId matches
             */

            // is an admin
            if (UserInfo.IsInRole(PortalSettings.AdministratorRoleName))
            {
                return true;
            }

            // is on the profile page
            if (((ModuleContext.PortalSettings.ActiveTab.ParentId == ModuleContext.PortalSettings.UserTabId) || (ModuleContext.TabId == ModuleContext.PortalSettings.UserTabId)) && UserIdParam > Null.NullInteger)
            {
                return true;
            }

            // is on a group page
            if (GroupIdParam > Null.NullInteger)
            {
                if (CurrentSocialGroup != null && CurrentSocialGroup.IsOwner)
                {
                    return true;
                }
            }

            return false;
        }

        protected bool AllowedToEditModule()
        {
            if (IsEditable && PortalSettings.UserMode == DotNetNuke.Entities.Portals.PortalSettings.Mode.Edit)
            {
                // the user has edit module/full control permissions
                return true;
            }

            if (IsInSocialMode())
            {

                if (UserId == UserIdParam)
                {
                    // the current userid matches the profile userid
                    return true;
                }

                if (GroupIdParam > Null.NullInteger)
                {
                    if (CurrentSocialGroup != null && CurrentSocialGroup.IsOwner)
                    {
                        // this is an owner of the group
                        return true;
                    }
                }

            }

            return false;
        }

        #endregion

    }

}